#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
生成前端背景图片资源的脚本
用于创建登录页面、首页等背景图片
"""

import os
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random

# 设置媒体文件根目录
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
FRONTEND_IMAGES_DIR = os.path.join(MEDIA_ROOT, 'frontend')


def create_gradient_background(width, height, color1, color2, direction='vertical'):
    """创建渐变背景"""
    base = Image.new('RGB', (width, height), color1)
    top = Image.new('RGB', (width, height), color2)
    mask = Image.new('L', (width, height))
    mask_data = []
    
    if direction == 'vertical':
        for y in range(height):
            mask_data.extend([int(255 * (y / height))] * width)
    else:  # horizontal
        for y in range(height):
            for x in range(width):
                mask_data.append(int(255 * (x / width)))
    
    mask.putdata(mask_data)
    base.paste(top, (0, 0), mask)
    return base


def add_geometric_patterns(img, width, height):
    """添加几何图案装饰"""
    draw = ImageDraw.Draw(img, 'RGBA')
    
    # 添加半透明圆形
    for _ in range(10):
        x = random.randint(0, width)
        y = random.randint(0, height)
        radius = random.randint(30, 150)
        color = random.choice([
            (255, 255, 255, 20),
            (255, 255, 255, 30),
            (0, 0, 0, 10),
            (0, 0, 0, 15)
        ])
        draw.ellipse([x - radius, y - radius, x + radius, y + radius], fill=color)
    
    return img


def create_login_background(filename, size=(1920, 1080)):
    """生成登录页面背景图片 - 温暖色调"""
    # 温暖的渐变色
    color1 = (255, 159, 122)  # 珊瑚橙
    color2 = (255, 218, 185)  # 桃色
    
    img = create_gradient_background(size[0], size[1], color1, color2, 'vertical')
    
    # 添加装饰图案
    img = add_geometric_patterns(img, size[0], size[1])
    
    # 轻微模糊处理，使背景更柔和
    img = img.filter(ImageFilter.GaussianBlur(2))
    
    # 绘制一些装饰元素
    draw = ImageDraw.Draw(img, 'RGBA')
    
    # 添加一些波浪线装饰
    for i in range(5):
        y = size[1] // 5 * (i + 1)
        points = []
        for x in range(0, size[0], 50):
            offset = random.randint(-20, 20)
            points.append((x, y + offset))
        
        if len(points) > 1:
            for j in range(len(points) - 1):
                draw.line([points[j], points[j + 1]], 
                         fill=(255, 255, 255, 30), width=3)
    
    # 保存图片
    os.makedirs(os.path.dirname(filename), exist_ok=True)
    img.save(filename, 'JPEG', quality=95)
    print(f"✓ 生成登录背景图片: {filename}")


def create_home_background(filename, size=(1920, 1080)):
    """生成首页背景图片 - 清新色调"""
    # 清新的蓝绿渐变
    color1 = (135, 206, 235)  # 天蓝色
    color2 = (144, 238, 144)  # 浅绿色
    
    img = create_gradient_background(size[0], size[1], color1, color2, 'diagonal')
    
    # 添加装饰图案
    draw = ImageDraw.Draw(img, 'RGBA')
    
    # 添加一些美食相关的几何图形
    # 大圆形（表示盘子）
    for i in range(8):
        x = random.randint(100, size[0] - 100)
        y = random.randint(100, size[1] - 100)
        radius = random.randint(60, 120)
        
        # 绘制半透明白色圆形
        draw.ellipse([x - radius, y - radius, x + radius, y + radius],
                    fill=(255, 255, 255, 25),
                    outline=(255, 255, 255, 50),
                    width=3)
    
    # 添加一些小圆点装饰
    for _ in range(50):
        x = random.randint(0, size[0])
        y = random.randint(0, size[1])
        radius = random.randint(3, 8)
        draw.ellipse([x - radius, y - radius, x + radius, y + radius],
                    fill=(255, 255, 255, 60))
    
    # 轻微模糊
    img = img.filter(ImageFilter.GaussianBlur(1))
    
    # 保存图片
    os.makedirs(os.path.dirname(filename), exist_ok=True)
    img.save(filename, 'JPEG', quality=95)
    print(f"✓ 生成首页背景图片: {filename}")


def create_banner_image(filename, text, size=(1200, 400)):
    """生成横幅图片"""
    # 活力橙色渐变
    color1 = (255, 140, 0)   # 深橙色
    color2 = (255, 215, 0)   # 金色
    
    img = create_gradient_background(size[0], size[1], color1, color2, 'horizontal')
    draw = ImageDraw.Draw(img, 'RGBA')
    
    # 添加装饰圆圈
    for _ in range(15):
        x = random.randint(0, size[0])
        y = random.randint(0, size[1])
        radius = random.randint(20, 80)
        draw.ellipse([x - radius, y - radius, x + radius, y + radius],
                    fill=(255, 255, 255, 30))
    
    # 尝试添加文字
    try:
        font = ImageFont.truetype("msyh.ttc", 80)
    except:
        try:
            font = ImageFont.truetype("arial.ttf", 80)
        except:
            font = ImageFont.load_default()
    
    # 绘制文字阴影
    bbox = draw.textbbox((0, 0), text, font=font)
    text_width = bbox[2] - bbox[0]
    text_height = bbox[3] - bbox[1]
    x = (size[0] - text_width) // 2
    y = (size[1] - text_height) // 2
    
    # 阴影
    draw.text((x + 3, y + 3), text, fill=(0, 0, 0, 100), font=font)
    # 文字
    draw.text((x, y), text, fill=(255, 255, 255, 255), font=font)
    
    # 保存图片
    os.makedirs(os.path.dirname(filename), exist_ok=True)
    img.save(filename, 'JPEG', quality=95)
    print(f"✓ 生成横幅图片: {filename} ({text})")


def main():
    """主函数"""
    print("=" * 60)
    print("开始生成前端背景图片...")
    print("=" * 60)
    
    # 创建前端图片目录
    frontend_dir = FRONTEND_IMAGES_DIR
    
    # 1. 生成登录页面背景
    print("\n[1/3] 生成登录页面背景...")
    create_login_background(os.path.join(frontend_dir, 'login_bg.jpg'))
    
    # 2. 生成首页背景
    print("\n[2/3] 生成首页背景...")
    create_home_background(os.path.join(frontend_dir, 'home_bg.jpg'))
    
    # 3. 生成横幅图片
    print("\n[3/3] 生成横幅图片...")
    create_banner_image(os.path.join(frontend_dir, 'banner.jpg'), '美食外卖平台')
    
    print("\n" + "=" * 60)
    print(f"✓ 完成！共生成 3 张前端背景图片")
    print(f"图片保存位置: {frontend_dir}")
    print("\n访问方式:")
    print("  登录背景: http://localhost:8000/media/frontend/login_bg.jpg")
    print("  首页背景: http://localhost:8000/media/frontend/home_bg.jpg")
    print("  横幅图片: http://localhost:8000/media/frontend/banner.jpg")
    print("=" * 60)


if __name__ == '__main__':
    main()

